import requestUrl from '../../utils/requestUtil.js';
const userToken = wx.getStorageSync('token');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //日期
    show: false,
    currentDate: 0,
    showYear: "",
    showmonth: "",
    showDay: "",
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //种植的skuNo
    skuNo:null,
    //种植方式索引
    plantingIndex:0,
    //当前选择
    plantingSelected:null,
    //种植方式数组
    plantingList:[],
    //种植方式的图片
    plantingPicture:[],
    //种植方式的视频
    plantingVideo:[],
    //上传的字段数组
    uploadTextField:[]
  },
  /**
   * 种植方式切换函数
   */
  onPlantingTap(e){
    this.setData({
      plantingIndex:e.target.dataset.index,
      plantingSelected:this.data.plantingList[e.target.dataset.index].modelName,
      plantingPicture:[],
      plantingVideo:[]
    })
    this.requestTemplate();
  },
  oninputText(e){
    let currentIndex = e.currentTarget.dataset.index;
    let temp = this.data.plantingList[this.data.plantingIndex].modelInfo;

    temp[currentIndex].i_value = e.detail.value;

    this.setData({
      uploadTextField:temp
    })
  },
  
  /**
   * 种植方式图片添加函数
   */
  plantingAfterRead(e) {
    const { file } = e.detail;
    const { plantingPicture = [] } = this.data;
    plantingPicture.push({ ...file, url: e.data });
    this.setData({ plantingPicture });
    let currentIndex = e.currentTarget.dataset.index;
    this.uploadMethod(file,currentIndex);
  },
  //上传模块复用
  uploadMethod(file,currentIndex){
    let that = this;
    wx.showLoading({
      title: '正在上传..',
    })
    wx.uploadFile({
      url: 'https://nhwechart.nsb-farmall.com/app/upload',
      filePath: file.url,
      name: 'file',
      formData:{
        params:{}
      },
      header: { 
        "content-Type": "multipart/form-data;charset=utf-8",
        'token':userToken
      },
       success(res) {
        //获取当前tab选择的数组
         let temp = that.data.plantingList[that.data.plantingIndex].modelInfo;
        
         if (temp[currentIndex].i_value == null || temp[currentIndex].i_value == "") {
              temp[currentIndex].i_value = [];
         }
         temp[currentIndex].i_value.push(JSON.parse(res.data).url);
         that.setData({
            uploadTextField:temp
         })
         wx.hideLoading()
       },
       fail(err) {
         console.log(err);
       }
    })
  },
  /**
   * 种植方式图片删除函数
   */
  plantingDeletePic(e) {
    const { plantingPicture = [] } = this.data;
    plantingPicture.splice(e.detail.index,1);
    this.setData({ plantingPicture });
    let currentIndex = e.currentTarget.dataset.index;
    let temp = this.data.plantingList[this.data.plantingIndex].modelInfo;
    temp[currentIndex].i_value.splice(e.detail.index,1);
    that.setData({
      uploadTextField:temp
    })
  },
  /**
  * 种植方式视频添加函数
  */
 plantingVideoAfterRead(e) {
   const { file } = e.detail;
   const { plantingVideo = [] } = this.data;
   plantingVideo.push({ ...file, url: e.data });
   this.setData({ plantingVideo });
   let currentIndex = e.currentTarget.dataset.index;
   this.uploadMethod(file,currentIndex);
 },
 /**
  * 种植方式视频删除函数
  */
 plantingVideoDeletePic(e) {
   //删除到显示数组
   const { plantingVideo = [] } = this.data;
   plantingVideo.splice(e.detail.index,1);
   this.setData({ plantingVideo });
   //删除到上传数组
   let currentIndex = e.currentTarget.dataset.index;
   let temp = this.data.plantingList[this.data.plantingIndex].modelInfo;
   temp[currentIndex].i_value.splice(e.detail.index,1);
   that.setData({
       uploadTextField:temp
   })
 },
  //时间输入
  //显示
  showPopup() {
    this.setData({
      show: true
    });
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onConfirm() {
    this.mathChangeDate(this.data.currentDate)
    this.setData({
      show: false,
    })
  },
  onCancel() {
    this.setData({
      show: false,
      currentDate: 0,
      showFormatDate: ""
    })
  },
  mathChangeDate(times) {
    var date = new Date(times);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    this.setData({
      showYear: year,
      showmonth: month < 10 ?'0'+month:month,
      showDay: day < 10 ?'0'+day:day
    })
  },
  //提交表单
  onSubmit(e){
    let that = this;
    let field = that.data.uploadTextField;
    var reg = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/;
    var regExp = new RegExp(reg);
    for (let index = 0; index < field.length; index++) {
      if(field[index].v_label == '160202'){
        if (!regExp.test(field[index].i_value)) {
          return wx.showToast({
            title: "时间格式错误",
            icon: "none"
          })
        }
      }
    }

    for (let index = 0; index < field.length; index++) {
      if(field[index].i_value == ''){
        return wx.showToast({
          title: '请填写完整信息',
          icon: "none"
        })
      }
    }
    
    
    field.push(this.data.plantingList[this.data.plantingIndex].modelName);
    requestUrl.requestUrl({
          url: "/app/plant/save",
          params: {
            "context": JSON.stringify(field),
            "skuNo": that.data.skuNo
          },
          method:"post",
          header:{
            token:userToken
          }
      }).then((data) => {
        wx.navigateBack()
      }).catch((errorMsg) => {
        console.log("error",errorMsg);
      })
  },

  //请求模板
  requestTemplate(){
    var that = this;
    requestUrl.requestUrl({
        url: "/app/gys/templates",
        params: {},
        method:"get",
        header:{
            token:userToken
        }
    }).then((data) => {
        let list = that.formatPlantList(data.data.list);
        that.setData({
          plantingList:list
        })
      }).catch((errorMsg) => {
      wx.showToast({
        title:'请重新加载',
        icon: 'none',    
      })
    })
  },
  
  formatPlantList(arr){
    let list = [];
    arr.forEach(item => {
      let obj = {
        coNo:item.coNo,
        id:item.id,
        instTime:item.instTime,
        instUserNo:item.instUserNo,
        modelInfo:JSON.parse(item.modelInfo),
        modelName:item.modelName,
        modelNo:item.modelNo,
        openType:item.openType,
        state:item.state,
        updtTime:item.updtTime,
        updtUserNo:item.updtUserNo
      }
      list.push(obj);
    });
    return list;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //将上个页面的值传过来
    this.setData({
      skuNo:options.skuNo
    })
    this.mathChangeDate(new Date().getTime());
    this.requestTemplate();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})